{% extends "index.html" %}

{% block title %}登录与注册{% endblock %}

{% block css %}
<style>
    /* 所有CSS样式都在#BloodSpiderBox中 */
    #BloodSpiderBox {
        width: 100%;
        height: 100vh;
        background: #f5f5f5;
        display: flex;
        align-items: center;
        justify-content: center;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
    }

    .login-container {
        width: 400px;
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        padding: 30px;
    }

    /* 表单标题 */
    .form-title {
        text-align: center;
        margin-bottom: 30px;
        font-size: 24px;
        font-weight: 600;
        color: #333;
    }

    /* 输入框样式 */
    .layui-input {
        border-radius: 4px;
        transition: all 0.3s;
    }

    .layui-input:focus {
        border-color: #1e9fff;
        box-shadow: 0 0 0 2px rgba(30, 159, 255, 0.2);
    }

    /* 按钮样式 */
    .layui-btn {
        border-radius: 4px;
        transition: all 0.3s;
    }

    .layui-btn-primary:hover {
        border-color: #1e9fff;
        color: #1e9fff;
    }

    /* 切换按钮 */
    .switch-tabs {
        display: flex;
        margin-bottom: 20px;
        border-bottom: 1px solid #e6e6e6;
    }

    .switch-tab {
        flex: 1;
        text-align: center;
        padding: 10px;
        cursor: pointer;
        color: #666;
        transition: all 0.3s;
    }

    .switch-tab.active {
        color: #1e9fff;
        border-bottom: 2px solid #1e9fff;
    }

    /* 表单组 */
    .form-group {
        margin-bottom: 20px;
    }

    .form-group label {
        display: block;
        margin-bottom: 8px;
        color: #333;
        font-weight: 500;
    }

    /* 错误提示 */
    .error-tip {
        color: #ff5722;
        font-size: 12px;
        margin-top: 5px;
        display: none;
    }

    /* 底部操作区 */
    .form-footer {
        margin-top: 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    /* 账号规则提示 */
    .account-rule {
        font-size: 12px;
        color: #999;
        margin-top: 5px;
    }

    /* 加载中动画 */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            display: none;
        }
        
        /* 禁用元素样式 */
        .disabled-element {
            pointer-events: none !important;
            opacity: 0.6 !important;
            cursor: not-allowed !important;
        }
        
        /* 为禁用状态下的输入框添加特殊样式 */
        .disabled-element.layui-input {
            background-color: #f5f5f5;
            border-color: #d2d2d2;
        }
        
        /* 为禁用状态下的按钮添加特殊样式 */
        .disabled-element.layui-btn {
            background-color: #d2d2d2;
            border-color: #d2d2d2;
            color: #666;
        }
        
        /* 密码显示切换按钮样式 */
        .password-toggle {
            position: relative;
            display: inline-block;
            width: 100%;
        }
        
        .password-toggle input {
            padding-right: 40px !important;
        }
        
        .password-toggle-btn {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #999;
            font-size: 14px;
            user-select: none;
        }
        
        .password-toggle-btn:hover {
            color: #1e9fff;
        }

    .loading-content {
        background: #fff;
        padding: 20px;
        border-radius: 4px;
        display: flex;
        align-items: center;
    }

    .loading-spinner {
        width: 20px;
        height: 20px;
        border: 2px solid #f3f3f3;
        border-top: 2px solid #1e9fff;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-right: 10px;
    }

    @keyframes spin {
        0% {
            transform: rotate(0deg);
        }

        100% {
            transform: rotate(360deg);
        }
    }
</style>
{% endblock %}

{% block body %}

<div id="BloodSpiderBox">
    <div class="login-container">
        <!-- 切换标签 -->
        <div class="switch-tabs">
            <div class="switch-tab active" data-target="login-form">登录</div>
            <div class="switch-tab" data-target="register-form">注册</div>
        </div>

        <!-- 登录表单 -->
        <div id="login-form" class="form-content">
            <h2 class="form-title"><span id="login-title">用户登录</span></h2>
            <form class="layui-form">
                <div class="form-group">
                    <label for="login-account">账号</label>
                    <input type="text" id="login-account" name="account" placeholder="请输入账号" class="layui-input">
                    <div class="error-tip" id="login-account-error">账号不能为空</div>
                    <div class="account-rule">账号必须为8-11位纯数字</div>
                </div>
                <div class="form-group">
                    <label for="login-password">密码</label>
                    <div class="password-toggle">
                        <input type="password" id="login-password" name="password" placeholder="请输入密码" class="layui-input">
                        <span class="password-toggle-btn" id="toggle-login-password">
                            <i class="layui-icon layui-icon-eye"></i>
                        </span>
                    </div>
                    <div class="error-tip" id="login-password-error">密码不能为空</div>
                </div>
                <div class="form-footer">
                    <button type="button" id="login-btn" class="layui-btn layui-btn-normal">登录</button>
                </div>
            </form>
        </div>

        <!-- 注册表单 -->
        <div id="register-form" class="form-content" style="display: none;">
            <h2 class="form-title"><span id="register-title">用户注册</span></h2>
            <form class="layui-form">
                <div class="form-group">
                    <label for="register-username">用户名</label>
                    <input type="text" id="register-username" name="username" placeholder="请输入用户名" class="layui-input">
                    <div class="error-tip" id="register-username-error">用户名不能为空</div>
                </div>
                <div class="form-group">
                    <label for="register-account">账号</label>
                    <input type="text" id="register-account" name="account" placeholder="请输入账号" class="layui-input">
                    <div class="error-tip" id="register-account-error">账号不能为空</div>
                    <div class="account-rule">账号必须为8-11位纯数字</div>
                </div>
                <div class="form-group">
                    <label for="register-password">密码</label>
                    <div class="password-toggle">
                        <input type="password" id="register-password" name="password" placeholder="请输入密码"
                            class="layui-input">
                        <span class="password-toggle-btn" id="toggle-register-password">
                            <i class="layui-icon layui-icon-eye"></i>
                        </span>
                    </div>
                    <div class="error-tip" id="register-password-error">密码不能为空</div>
                </div>
                <div class="form-footer">
                    <button type="button" id="register-btn" class="layui-btn layui-btn-normal">注册</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 加载中遮罩 -->
    <div class="loading-overlay" id="loading-overlay">
        <div class="loading-content">
            <div class="loading-spinner"></div>
            <span>处理中...</span>
        </div>
    </div>
</div>

{% endblock %}



{% block js %}
{% include '组件/登录通用函数.html' %}
<script>

    document.addEventListener('DOMContentLoaded', function () {
        // 页面配置 - 可根据不同项目修改这些变量
        const pageConfig = {
            loginTitle: '用户登录',
            registerTitle: '用户注册',
            baseApiUrl: BloodSpiderBaseUrl + '/api/user/'
        };

        /**
         * 检查URL参数是否满足要求
         * @returns {boolean} 是否满足条件
         */
        function checkUrlParams() {
            try {
                // 使用工具函数获取URL参数
                const urlInfo = window.BloodSpiderFunction_getUrlParams();
                const params = urlInfo.params;
                
                // 检查是否同时存在source=TKShopping和NotificationReceivingAPI参数
                if (params.source && params.NotificationReceivingAPI) {
                    const notificationValue = params.NotificationReceivingAPI;
                    
                    // 验证NotificationReceivingAPI是否为base64编码（没有等号）
                    // Base64编码通常只包含A-Z, a-z, 0-9, +, /字符，且不包含等号
                    const base64Pattern = /^[A-Za-z0-9+/]+$/;
                    return base64Pattern.test(notificationValue);
                }
                return false;
            } catch (error) {
                console.error('URL参数检查失败:', error);
                return false;
            }
        }

        /**
         * 禁用或启用页面上的所有交互元素
         * @param {boolean} disable - 是否禁用
         */
        function setPageInteraction(disable) {
            const interactiveElements = document.querySelectorAll(
                'input, button, .switch-tab'
            );
            
            interactiveElements.forEach(element => {
                if (disable) {
                    // 禁用元素
                    element.disabled = true;
                    element.classList.add('disabled-element');
                    // 移除事件监听器的方式是添加一层覆盖
                    if (element.tagName === 'INPUT' || element.tagName === 'BUTTON') {
                        element.style.cursor = 'not-allowed';
                        element.style.opacity = '0.6';
                    } else if (element.classList.contains('switch-tab')) {
                        element.style.cursor = 'not-allowed';
                        // 阻止点击事件冒泡
                        element.addEventListener('click', function(e) {
                            e.stopPropagation();
                            e.preventDefault();
                        }, true);
                    }
                } else {
                    // 启用元素
                    element.disabled = false;
                    element.classList.remove('disabled-element');
                    element.style.cursor = '';
                    element.style.opacity = '1';
                }
            });
        }

        // 设置页面标题
        function setPageTitles() {
            document.getElementById('login-title').textContent = pageConfig.loginTitle;
            document.getElementById('register-title').textContent = pageConfig.registerTitle;
        }

        // 防抖函数
        function debounce(fn, delay) {
            let timer = null;
            return function () {
                const context = this;
                const args = arguments;
                clearTimeout(timer);
                timer = setTimeout(() => {
                    fn.apply(context, args);
                }, delay);
            };
        }

        // 显示错误提示
        function showError(elementId, message) {
            const errorElement = document.getElementById(elementId);
            errorElement.textContent = message;
            errorElement.style.display = 'block';
        }

        // 隐藏错误提示
        function hideError(elementId) {
            const errorElement = document.getElementById(elementId);
            errorElement.style.display = 'none';
        }

        // 显示加载中
        function showLoading() {
            document.getElementById('loading-overlay').style.display = 'flex';
        }

        // 隐藏加载中
        function hideLoading() {
            document.getElementById('loading-overlay').style.display = 'none';
        }

        // 切换表单
        function setupFormSwitch() {
            const tabs = document.querySelectorAll('.switch-tab');
            const forms = document.querySelectorAll('.form-content');

            tabs.forEach(tab => {
                tab.addEventListener('click', function () {
                    // 移除所有active状态
                    tabs.forEach(t => t.classList.remove('active'));
                    forms.forEach(f => f.style.display = 'none');

                    // 添加当前active状态
                    this.classList.add('active');
                    const target = this.getAttribute('data-target');
                    document.getElementById(target).style.display = 'block';
                });
            });
        }

        // 验证账号格式（8-11位纯数字）
        function validateAccount(account) {
            if (!account) {
                return { valid: false, message: '账号不能为空' };
            }
            if (!/^\d+$/.test(account)) {
                return { valid: false, message: '账号必须为纯数字' };
            }
            if (!(account.length >= 8 && account.length <= 11)) {
                return { valid: false, message: '账号长度必须在8-11位之间' };
            }
            return { valid: true };
        }

        // 验证密码
        function validatePassword(password) {
            if (!password) {
                return { valid: false, message: '密码不能为空' };
            }
            return { valid: true };
        }

        // 验证用户名
        function validateUsername(username) {
            if (!username) {
                return { valid: false, message: '用户名不能为空' };
            }
            return { valid: true };
        }

        // 登录表单验证
        function validateLoginForm() {
            const account = document.getElementById('login-account').value;
            const password = document.getElementById('login-password').value;

            let isValid = true;

            // 验证账号
            const accountResult = validateAccount(account);
            if (!accountResult.valid) {
                showError('login-account-error', accountResult.message);
                isValid = false;
            } else {
                hideError('login-account-error');
            }

            // 验证密码
            const passwordResult = validatePassword(password);
            if (!passwordResult.valid) {
                showError('login-password-error', passwordResult.message);
                isValid = false;
            } else {
                hideError('login-password-error');
            }

            return isValid;
        }

        // 注册表单验证
        function validateRegisterForm() {
            const username = document.getElementById('register-username').value;
            const account = document.getElementById('register-account').value;
            const password = document.getElementById('register-password').value;

            let isValid = true;

            // 验证用户名
            const usernameResult = validateUsername(username);
            if (!usernameResult.valid) {
                showError('register-username-error', usernameResult.message);
                isValid = false;
            } else {
                hideError('register-username-error');
            }

            // 验证账号
            const accountResult = validateAccount(account);
            if (!accountResult.valid) {
                showError('register-account-error', accountResult.message);
                isValid = false;
            } else {
                hideError('register-account-error');
            }

            // 验证密码
            const passwordResult = validatePassword(password);
            if (!passwordResult.valid) {
                showError('register-password-error', passwordResult.message);
                isValid = false;
            } else {
                hideError('register-password-error');
            }

            return isValid;
        }

        // 登录提交
        function submitLogin() {
            if (!validateLoginForm()) {
                return;
            }

            const account = document.getElementById('login-account').value;
            const password = document.getElementById('login-password').value;

            showLoading();

            // 使用axios发送请求
            axios.post(pageConfig.baseApiUrl + 'login/', {
                account: account,
                password: password
            }, {
                transformRequest: [function (data) {
                    let formData = '';
                    for (const key in data) {
                        if (formData) formData += '&';
                        formData += encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
                    }
                    return formData;
                }]
            })
                .then(function (response) {
                    hideLoading();
                    if (response.data.code === 0) {
                        layer.msg('登录成功');
                        console.log('登录成功:', response.data);
                        // 调用登录成功后的回调函数
                        handleLoginSuccess(response.data);
                        // 可以在这里跳转到首页或其他页面
                    } else {
                        // 优先使用data内的错误字段
                        if (response.data.data && typeof response.data.data === 'object') {
                            const errorMsg = Object.values(response.data.data)[0];
                            layer.msg(errorMsg || '登录失败');
                        } else {
                            layer.msg(response.data.message || '登录失败');
                        }
                    }
                })
                .catch(function (error) {
                    hideLoading();
                    layer.msg('登录请求失败');
                    console.error('登录错误:', error);
                });
        }

        // 注册提交
        function submitRegister() {
            if (!validateRegisterForm()) {
                return;
            }

            const username = document.getElementById('register-username').value;
            const account = document.getElementById('register-account').value;
            const password = document.getElementById('register-password').value;

            // 在控制台打印表单数据
            console.log('注册表单数据:', { username, account, password });

            showLoading();

            // 使用axios发送请求
            axios.post(pageConfig.baseApiUrl + 'create/', {
                username: username,
                account: account,
                password: password
            }, {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                transformRequest: [function (data) {
                    let formData = '';
                    for (const key in data) {
                        if (formData) formData += '&';
                        formData += encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
                    }
                    return formData;
                }]
            })
                .then(function (response) {
                    hideLoading();
                    if (response.data.code === 0) {
                        layer.msg('注册成功');
                        console.log('注册成功:', response.data);
                        // 注册成功后可以切换到登录表单
                        document.querySelector('.switch-tab[data-target="login-form"]').click();
                    } else {
                        // 优先使用data内的错误字段
                        if (response.data.data && typeof response.data.data === 'object') {
                            const errorMsg = Object.values(response.data.data)[0];
                            layer.msg(errorMsg || '注册失败');
                        } else {
                            layer.msg(response.data.message || '注册失败');
                        }
                    }
                })
                .catch(function (error) {
                    hideLoading();
                    layer.msg('注册请求失败');
                    console.error('注册错误:', error);
                });
        }

        // 设置输入防抖验证
        function setupInputValidation() {
            // 登录表单输入验证
            document.getElementById('login-account').addEventListener('input', debounce(function () {
                const account = this.value;
                const result = validateAccount(account);
                if (account && !result.valid) {
                    showError('login-account-error', result.message);
                } else {
                    hideError('login-account-error');
                }
            }, 300));

            document.getElementById('login-password').addEventListener('input', debounce(function () {
                const password = this.value;
                const result = validatePassword(password);
                if (password && !result.valid) {
                    showError('login-password-error', result.message);
                } else {
                    hideError('login-password-error');
                }
            }, 300));

            // 注册表单输入验证
            document.getElementById('register-username').addEventListener('input', debounce(function () {
                const username = this.value;
                const result = validateUsername(username);
                if (username && !result.valid) {
                    showError('register-username-error', result.message);
                } else {
                    hideError('register-username-error');
                }
            }, 300));

            document.getElementById('register-account').addEventListener('input', debounce(function () {
                const account = this.value;
                const result = validateAccount(account);
                if (account && !result.valid) {
                    showError('register-account-error', result.message);
                } else {
                    hideError('register-account-error');
                }
            }, 300));

            document.getElementById('register-password').addEventListener('input', debounce(function () {
                const password = this.value;
                const result = validatePassword(password);
                if (password && !result.valid) {
                    showError('register-password-error', result.message);
                } else {
                    hideError('register-password-error');
                }
            }, 300));
        }

        // 切换密码显示/隐藏
        function togglePasswordVisibility(inputId, toggleBtnId) {
            const passwordInput = document.getElementById(inputId);
            const toggleBtn = document.getElementById(toggleBtnId);
            const icon = toggleBtn.querySelector('i');
            
            toggleBtn.addEventListener('click', function() {
                const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
                passwordInput.setAttribute('type', type);
                
                // 切换图标
                if (type === 'text') {
                    icon.classList.remove('layui-icon-eye');
                    icon.classList.add('layui-icon-eye-invisible');
                } else {
                    icon.classList.remove('layui-icon-eye-invisible');
                    icon.classList.add('layui-icon-eye');
                }
            });
        }
        
        // 设置按钮点击事件
        function setupButtonEvents() {
            document.getElementById('login-btn').addEventListener('click', submitLogin);
            document.getElementById('register-btn').addEventListener('click', submitRegister);
            
            // 设置密码显示/隐藏切换
            togglePasswordVisibility('login-password', 'toggle-login-password');
            togglePasswordVisibility('register-password', 'toggle-register-password');

            // 添加回车键提交
            document.getElementById('login-password').addEventListener('keyup', function (event) {
                if (event.key === 'Enter') {
                    submitLogin();
                }
            });

            document.getElementById('register-password').addEventListener('keyup', function (event) {
                if (event.key === 'Enter') {
                    submitRegister();
                }
            });
        }

        // 页面加载完成后初始化
        window.onload = function () {
            setPageTitles();
            setupFormSwitch();
            setupInputValidation();
            setupButtonEvents();
            
            // 检查URL参数是否满足要求
            const paramsValid = checkUrlParams();
            
            // 如果参数不满足要求，禁用所有交互
            if (!paramsValid) {
                setPageInteraction(true);
                // 显示提示信息
                layer.msg('当前页面访问受限');
                console.log('页面访问受限：URL参数不符合要求');
            }
        };

   
    })


</script>
{% endblock %}